package main

import (
	"RSA/generatekey"
	"RSA/rsadecrypt"
	"RSA/rsaencrypt"
	"RSA/utils"
	"bufio"
	"flag"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var bitSize string
var privateKeyFileName string
var publicKeyFileName string
var plainFileName string
var plainString string
var cipherFileName string

func init() {
	flag.StringVar(&bitSize, "bs", "", "密钥bit长度")
	flag.StringVar(&privateKeyFileName, "pvkf", "", "指定要生成(或使用)私钥文件名")
	flag.StringVar(&publicKeyFileName, "pukf", "", "指定要生成(或使用)公钥钥文件名")
	flag.StringVar(&plainFileName, "plaf", "", "明文文件名")
	flag.StringVar(&plainString, "plas", "", "明文字符串")
	flag.StringVar(&cipherFileName, "cipf", "", "密文文件名")
	flag.Parse()
}

func main() {
	s := os.Args
	bsbool := utils.FindElement(s, "-bs")
	pvkfbool := utils.FindElement(s, "-pvkf")
	pukfbool := utils.FindElement(s, "-pukf")
	plafbool := utils.FindElement(s, "-plaf")
	plasbool := utils.FindElement(s, "-plas")
	cipfbool := utils.FindElement(s, "-cipf")

	pl := utils.NewParameterList(bsbool, pvkfbool, pukfbool, plafbool, plasbool, cipfbool)
	u := pl.ParameterValue()
	switch u {
	// 生成指定长度的密钥
	case 56:
		bs, _ := strconv.Atoi(bitSize)
		generatekey.MakeKey(bs, privateKeyFileName, publicKeyFileName)
	// 根据私钥文件产生公钥文件
	case 24:
		generatekey.GeneratePublibKey(privateKeyFileName, publicKeyFileName)
	// 加密明文文件输出到密文文件
	case 13:
		f, _ := os.Open(plainFileName)
		defer f.Close()
		CipherBytes, err := rsaencrypt.Encrypt(publicKeyFileName, f)
		if err != nil {
			fmt.Println(err.Error())
			return
		}
		cf, _ := os.Create(cipherFileName)
		defer cf.Close()
		w := bufio.NewWriter(cf)
		w.Write(CipherBytes)
		w.Flush()
	// 加密明文字符串输出到密文文件
	case 11:
		r := strings.NewReader(plainString)
		CipherBytes, err := rsaencrypt.Encrypt(publicKeyFileName, r)
		if err != nil {
			fmt.Println(err.Error())
		}
		f, _ := os.Create(cipherFileName)
		defer f.Close()
		w := bufio.NewWriter(f)
		w.Write(CipherBytes)
		w.Flush()
	// 解密密文文件输出到文件
	case 21:
		PlainTextBytes, err := rsadecrypt.Decrypt(privateKeyFileName, cipherFileName)
		if err != nil {
			fmt.Println(err.Error())
		}
		f, _ := os.Create(plainFileName)
		defer f.Close()
		w := bufio.NewWriter(f)
		w.Write(PlainTextBytes)
		w.Flush()
	// 解密密文文件输出到屏幕
	case 17:
		PlainTextBytes, err := rsadecrypt.Decrypt(privateKeyFileName, cipherFileName)
		if err != nil {
			fmt.Println(err.Error())
		}
		fmt.Println(string(PlainTextBytes))
	default:
		flag.PrintDefaults()
	}

}
